package com.xs.langchain4j_springboot.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xs.langchain4j_springboot.config.FootBallAssistant;
import dev.langchain4j.service.TokenStream;
import dev.langchain4j.service.tool.ToolExecution;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.time.LocalDate;

//@RequestMapping("/football")
@RequestMapping("/demo")
@RestController
public class FootballController {

    @Resource
    private FootBallAssistant footBallAssistant;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @RequestMapping(value = "/chat", produces = "text/stream;charset=UTF-8")
    public Flux<String> stream(@RequestParam String message, @RequestParam String userId) {

        TokenStream stream = footBallAssistant.chat(userId, message, LocalDate.now().toString());

        return Flux.create(sink -> {

            stream.onPartialResponse(s -> sink.next(s))
                    .onToolExecuted((ToolExecution toolExecution) -> {

                        sink.next("正在执行工具: " + toolExecution.request().name()+"\n");
                        sink.next("工具参数: " + toolExecution.request().arguments()+"\n");
                        sink.next("工具执行结果: " + toolExecution.result()+"\n");

                    })

                    .onCompleteResponse(c -> sink.complete())
                    .onError(sink::error)
                    .start();

        });

    }

}
